package org.tiny.spring.core.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by LiuYi on 2018/7/27 14:33
 * Bean工具类
 */
public abstract class TinyBeanUtil {

    /**
     * 利用反射java反射特性将bean转换为Map
     * @param bean
     * @param excludeParam
     * @return
     */
    public static Map<String, Object> beanToMap(Object bean, Set<String> excludeParam){
        Map<String, Object> map = new HashMap<>();
        try {
            Class beanClass = bean.getClass();
            Field[] fields = beanClass.getDeclaredFields();
            for (Field field : fields) {
                boolean accessible = field.isAccessible();
                field.setAccessible(true);
                String fieldName = field.getName();
                if (excludeParam!=null && excludeParam.contains(fieldName))
                    continue;
                Object value = field.get(bean);
                map.put(fieldName, value);
                field.setAccessible(accessible);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}